from django.http import JsonResponse
from django.views import View

from cart.cart import Cart as ProductCart
# Create your views here.
from products.models import Product


class Cart(View):
    def post(self, request, product_id):
        """添加商品到购物车"""
        cart = ProductCart(request)
        try:
            product = Product.objects.get(id=product_id)
        except Product.DoesNotExist:
            return JsonResponse({"msg": "product do not exist."})
        else:
            data = request.POST
            cart.add(product=product, n=data.get['quantity'])
            return JsonResponse({'msg': 'ok'})

    def put(self, request, product_id):
        """添加商品到购物车"""
        cart = ProductCart(request)
        try:
            product = Product.objects.get(id=product_id)
        except Product.DoesNotExist:
            return JsonResponse({"msg": "product do not exist."})
        else:
            data = request.POST
            cart.update(product=product, n=data.get['quantity'])
            return JsonResponse({'msg': 'ok'})

    def delete(self, request, product_id):
        cart = ProductCart(request)
        try:
            product = Product.objects.get(id=product_id)
        except Product.DoesNotExist:
            return JsonResponse({"msg": "product do not exist."})
        else:
            cart.remove(product)
            return JsonResponse({'msg': 'ok'})

    def get(self, request):

        cart = ProductCart(request)
        return JsonResponse({'cart': cart.to_dict()})
